"""
按分类查询图书接口路由
"""

from fastapi import APIRouter, Query
from fastapi.responses import JSONResponse
from typing import Optional
from db.operations import CategoryBookQuery
from model.book_model import BookListResponse, Book, MainCategoryResponse

# 创建分类相关的子路由
router = APIRouter(
    prefix="/categories",
    tags=["categories"],
    responses={404: {"description": "Not found"}},
)


@router.get("/", summary="分类查询接口信息")
async def get_categories_info():
    """获取分类查询接口信息和使用示例"""
    api_info = {
        "message": "按分类查询图书API接口",
        "endpoints": {
            "GET /api/categories/": "获取分类查询接口信息",
            "GET /api/categories/search": "按分类查询书籍（支持分页）",
            "GET /api/categories/main": "获取所有主分类列表",
        },
        "examples": {
            "查询所有书籍（分页）": {
                "url": "/api/categories/search?page=1&limit=10",
                "description": "获取第1页，每页10本书",
            },
            "按主分类查询": {
                "url": "/api/categories/search?main_category=文学&page=1&limit=5",
                "description": "查询文学类书籍，第1页，每页5本",
            },
            "按子分类查询": {
                "url": "/api/categories/search?sub_category=人工智能&page=1&limit=10",
                "description": "查询当代小说类书籍",
            },
            "按主分类和子分类查询": {
                "url": "/api/categories/search?main_category=计算机&sub_category=人工智能&page=1&limit=10",
                "description": "查询计算机类下的人工智能书籍，第1页，每页10本",
            },
            "获取分类列表": {
                "url": "/api/categories/main",
                "description": "获取所有主分类列表",
            },
        },
        "parameters": {
            "page": "页码，从1开始，默认1",
            "limit": "每页数量，范围1-50，默认10",
            "main_category": "主分类名称（可选）",
            "sub_category": "子分类名称（可选）",
        },
    }

    return JSONResponse(status_code=200, content=api_info)


@router.get("/search", summary="按分类查询书籍")
async def get_books_by_category(
    page: int = Query(1, ge=1, description="页码，从1开始"),
    limit: int = Query(10, ge=1, le=50, description="每页数量，最大50"),
    main_category: Optional[str] = Query(None, description="主分类"),
    sub_category: Optional[str] = Query(None, description="子分类"),
):
    """
    按分类查询书籍，支持分页（使用原生SQL优化性能）
    """
    try:
        # 使用优化的分类查询类
        category_query = CategoryBookQuery()

        total, books_list = await category_query.query_books_by_category(
            main_category=main_category,
            sub_category=sub_category,
            page=page,
            limit=limit,
        )
        books_list = [Book(**book) for book in books_list]

        return JSONResponse(
            status_code=200,
            content=BookListResponse(
                message="查询成功",
                books_list=books_list,
                total=total,
                page=page,
                limit=limit,
            ).model_dump(),
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=BookListResponse(
                message=f"查询失败: {str(e)}",
                books_list=[],
                total=0,
                page=page,
                limit=limit,
            ).model_dump(),
        )


@router.get("/main", summary="获取所有主分类")
async def get_main_categories():
    """获取所有主分类列表"""
    try:
        category_query = CategoryBookQuery()
        main_categories = await category_query.get_all_main_categories()

        return JSONResponse(
            status_code=200,
            content=MainCategoryResponse(
                message="获取主分类成功",
                count=len(main_categories),
                main_category_list=main_categories,
            ).model_dump(),
        )
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=MainCategoryResponse(
                message=f"获取主分类失败: {str(e)}",
                count=0,
                main_category_list=[],
            ).model_dump(),
        )
